﻿using System.Windows;
using System.Windows.Data;

namespace Songhay.Wpf.Mvvm.Extensions
{
    /// <summary>
    /// Extension methods for <see cref="System.Windows.FrameworkElement"/>.
    /// </summary>
    public static class FrameworkElementExtensions
    {
        /// <summary>
        /// Does the validation.
        /// </summary>
        /// <param name="frameworkElement">The framework element.</param>
        /// <param name="dependencyProperty">The dependency property.</param>
        public static void DoValidation(this FrameworkElement frameworkElement, DependencyProperty dependencyProperty)
        {
            var expression = frameworkElement.GetBindingExpression(dependencyProperty);
            var binding = expression.ParentBinding;
            if(binding.ValidatesOnDataErrors)
            {
                expression.UpdateSource();
            }
            else
            {
                var newBinding = new Binding
                {
                    ElementName = binding.ElementName,
                    Mode = binding.Mode,
                    Path = binding.Path,
                    UpdateSourceTrigger = binding.UpdateSourceTrigger,
                    ValidatesOnDataErrors = true
                };
                frameworkElement.SetBinding(dependencyProperty, newBinding);
            }
        }
    }
}
